<template>
    <div class="app-container">

        <!--图片信息from表单查询信息 -->
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
            <el-form-item :label="$t('vehicle.type.vehicleModel')" prop="vehicleTypeId">
                <el-select v-model="queryParams.vehicleTypeId" :placeholder="$t('vehicle.type.placeholder.vehicleModel')">
                    <el-option v-for="dict in typeList" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini"
                    @click="handleQuery">{{ $t('common.button.query') }}</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('common.button.reset') }}</el-button>
            </el-form-item>
        </el-form>


        <!--图片新增入口-->
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['vehicle:role:add']">{{ $t('common.button.add') }}</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>


        <!--图片Table信息  -->
        <el-table v-loading="loading" border :data="tableData" style="width: 100%">
            <el-table-column prop="id" label="ID"></el-table-column>
            <el-table-column prop="vehicleTypeName" :label="$t('vehicle.type.vehicleModel')"></el-table-column>
            <el-table-column prop="colorDescription" :label="$t('vehicle.imgpairing.standard')"></el-table-column>
            <el-table-column prop="imgAddress" :label="$t('vehicle.imgpairing.pictureAddress')"></el-table-column>
            <el-table-column :label="$t('vehicle.imgpairing.PictureDisplay')" width="230">
                <template slot-scope="scope">
                    <image-preview :src="scope.row.imgAddress" :height="88" />
                </template>
            </el-table-column>
            <el-table-column fixed="right" :label="$t('common.table.operate')" width="100">
                <template slot-scope="scope">
                    <el-button @click="handleClick(scope.row)" type="text" size="small">{{ $t('common.button.edit')
                    }}</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['vehicle:type:remove']">{{ $t('common.button.remove') }}</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--分页-->
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />


        <!-- 新增OR修改表单 -->
        <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body @close="cancel">
            <el-form ref="form" :model="form" :rules="rules" label-width="125px">
                <el-form-item :label="$t('vehicle.type.vehicleModel')" prop="vehicleTypeId">
                    <template v-if="title == $t('common.button.add')">
                        <el-select v-model="form.vehicleTypeId" :placeholder="$t('vehicle.type.placeholder.vehicleModel')" clearable size="small" style="width:100%">
                            <el-option v-for="dict in typeList" :key="dict.value" :label="dict.label" :value="dict.value" />
                        </el-select>
                    </template>
                    <template  v-else>
                        <el-select v-model="form.vehicleTypeId" :placeholder="$t('vehicle.type.placeholder.vehicleModel')" disabled size="small" style="width:100%">
                            <el-option v-for="dict in typeList" :key="dict.value" :label="dict.label" :value="dict.value" />
                        </el-select>
                    </template>
                </el-form-item>
                <el-form-item :label="$t('vehicle.imgpairing.standard')" prop="colorDescription">
                    <el-input v-model="form.colorDescription" :placeholder="$t('vehicle.imgpairing.placeholder.cloreName')"
                        :maxlength="11" show-word-limit clearable :style="{ width: '100%' }"></el-input>
                </el-form-item>
                <el-form-item :label="$t('vehicle.imgpairing.PictureDisplay')" required>
                    <el-upload class="avatar-uploader" accept=".jpg" ref='upload' :limit="1" :headers="upload.headers"
                        :action="upload.url" :on-success='handleFileSuccess' :before-upload="beforeUpload"
                        :auto-upload="true" :data="form">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submit">{{ $t('common.dialog.confirm') }}</el-button>
                <el-button @click="cancel">{{ $t('common.dialog.cancel') }}</el-button>
            </div>
        </el-dialog>


    </div>
</template>

<script>
import { listType } from "@/api/vehicle/type/data";
import { getToken } from "@/utils/auth";
import { ListImg, addImg, updateImg, getInfo,deleteImg } from "@/api/vehicle/data";
export default {
    name: "imgpairing",
    data() {
        return {
            typeList: [],
            title: '',
            // 总条数
            total: 0,
            open: false,
            loading: false,
            showSearch: true,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                vehicleModel: ""
            },
            tableData: [],
            form: {
                vehicleTypeId: undefined,
                imgAddress: "",
                colorConversion: "",
                colorDescription: "",
            },
            rules: {
                 vehicleTypeId: [
                    { required: true, message: this.$t('vehicle.type.rules.type'), trigger: ["change","blur"] }
                ],
                colorDescription:[
                    { required: true, message: this.$t('vehicle.imgpairing.rules.color'), trigger: "blur" }
                ]               
            },
            upload: {
                headers: { Authorization: "Bearer " + getToken() },
                url: process.env.VUE_APP_BASE_API + "/vehicle/img/upload",
            },
            fileaddress: null,
            imageUrl: null
        }
    },
    computed: {},
    watch: {},
    created() {
        this.getList();
        this.getTypeList();
    },
    mounted() { },
    methods: {

        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },

        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },

        getList() {
            this.loading = true;
            ListImg(this.queryParams).then(response => {
                this.tableData = response.rows;
                this.total = response.total;
                this.loading = false;
            })
        },

        handleAdd() {
            this.reset();
            this.open = true;
            this.title = this.$t('common.button.add');
        },

        handleImport() {

        },

        handleClick(row) {
            this.loading = true;
            this.reset();
            const id = row.id || this.ids
            getInfo(id).then(response => {
                this.loading = false;
                this.form = response.data;
                this.imageUrl = response.data.imgAddress;
                this.open = true;
                this.title = this.$t('common.button.edit');
            });
        },
        // 表单重置
        reset() {
            this.form = {
                id: undefined,
                typeId: undefined,
                colorConversion: undefined,
                createBy: undefined,
                updateBy: undefined,
                createTime: undefined,
                updateTime: undefined
            };
            this.imageUrl = null;
            this.resetForm("form");
        },

        submit() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    this.buttonLoading = true;
                    this.form.imgAddress = this.fileaddress;
                    if (this.form.id != null) {
                        updateImg(this.form).then(response => {
                            this.$modal.msgSuccess("Successful");
                            this.open = false;
                            this.getList();
                        }).finally(() => {
                            this.buttonLoading = false;
                        });
                    } else {
                        addImg(this.form).then(response => {
                            this.$modal.msgSuccess("Successful");
                            this.open = false;
                            this.getList();
                        }).finally(() => {
                            this.buttonLoading = false;
                        });
                    }
                }
            });
        },

        cancel() {
            this.open = false;
            this.$refs.upload.clearFiles();
        },

        // 下面是图片上传功能
        handleFileSuccess(response, file) {
            this.fileaddress = response;
            this.imageUrl = URL.createObjectURL(file.raw);// 将上传成功后的图片URL赋值给imageUrl
        },

        //图片格式校验判断
        beforeUpload(file) {
            // 校验文件类型为图片
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error(this.$t('vehicle.imgpairing.placeholder.type'));
            }
            if (!isLt2M) {
                this.$message.error(this.$t('vehicle.imgpairing.placeholder.verify'));
            }
            return isJPG && isLt2M;
        },
        getTypeList() {
            listType().then(response => {
                this.typeList = response.rows.map(item => {
                    return {
                        label: item.typeName,
                        value: item.id
                    }
                })
            })
        },
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal.confirm(this.$t("vehicle.imgpairing.confirmDelete",{name:row.vehicleTypeName})).then((res) => {
                this.loading = true;
                return deleteImg(ids);
            }).then(res => {
                if (res.code != 200) {
                    this.loading = false;
                    this.getList();
                    this.$message.error(this.$t("common.operate.tip.fail"))

                }else{
                    this.loading = false;
                    this.getList();
                    this.$modal.deleteSuccess();
                    this.$message.success(this.$t("common.operate.tip.deleteSuccess"))


                }
                
            }).catch(() => {
            }).finally(() => {
                this.loading = false;
            });
            // deleteImg(row.id).then(res =>{
            //     if (res.code != 200) {
            //         this.$message.error(this.$t("common.operate.tip.fail"))
            //     }else{
            //         this.$message.success(this.$t("common.operate.tip.deleteSuccess"))
            //         this.getList();
            //     }
            // })

        }
    }
}
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
